<template>
	<view>
		<view style="display:none">
			<image @load="onImageLoad" :id="item.id" :src="item.pic" v-for="(item,_index) in images" :key="index"></image>
		</view>
		<scroll-view @scrolltolower="loadImages" scroll-y="true" :style="{height:scrollH+'px'}">
			<view style="width:100%">
				<view class="img_item">
					<view v-for="(item,index) in col1" :key="index">
						<image :src="item.pic" style="width:100%;" :style="{height:item.height+'px'}" @click="onImageClick(item.pic)"></image>
					</view>
				</view>
				<view class="img_item">
					<view v-for="(item,index) in col2" :key="index">
						<image :src="item.pic" style="width:100%;" :style="{height:item.height+'px'}" @click="onImageClick(item.pic)"></image>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	var n = 0,
		a = 0;
	export default {
		data() {
			return {
				scrollH: 0,
				imgWidth: 0,
				loadingCount: 0,
				images: [],
				imageData: [],
				col1: [],
				col2: []
			};
		},
		onLoad() {
			uni.showLoading({
				title:'加载中...'
			})
			uni.getSystemInfo({
				success: res => {
					var imgWidth = .48 * res.windowWidth,
						scrollH = res.windowHeight;
					this.scrollH = scrollH
					this.imgWidth = imgWidth
					this.getImageData();
				}
			});
		},
		methods: {
			getImageData() {
				uniCloud.callFunction({
					name: 'json-data',
					data: {
						action: 'beauty'
					},
					success: res => {
						console.log(res)
						let imageData = res.result
						this.imageData = imageData
						this.loadImages()
						uni.hideLoading()
					}
				})
			},
			loadImages() {
				let data = this.imageData
				let flag = "img-" + new Date()
				for (let i = 0; i < data.length; i++) {
					data[i].id = flag + "-" + i;
				}
				console.log(data.length)
				this.loadingCount = data.length
				this.images = data
			},
			onImageLoad(e) {
				console.log(e);
				for (var t = e.currentTarget.id, i = e.detail.width, o = e.detail.height * (this.imgWidth / i), c = this.images,
						l = null, p = 0; p < c.length; p++) {
					var r = c[p];
					if (r.id === t) {
						l = r;
						break;
					}
				}
				l.height = o;
				var g = this.loadingCount - 1,
					h = this.col1,
					m = this.col2;
				n <= a ? (n += o, h.push(l)) : (a += o, m.push(l));
				var v = {
					loadingCount: g,
					col1: h,
					col2: m
				};
				g || (v.images = []), this.loadingCount = g, this.col1 = h, this.col2 = m;
			},
			onImageClick(current) {
				let urls = [current]
				wx.previewImage({
					current,
					urls
				})
			}
		}
	}
</script>

<style>
	.img_item {
		width: 48%;
		margin: 1%;
		display: inline-block;
		vertical-align: top;
	}
</style>
